package org.apache.ocean;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ChangedUtil<K,V> {
	public Map<K,V> removed = new HashMap<K,V>();
	public Map<K,V> added = new HashMap<K,V>();
	public Map<K,V> changed = new HashMap<K,V>();
	public Map<K,V> newLocal;
	public Map<K,V> toDownload;
	
	public boolean hasChanges() {
		if (removed.size() > 0 || added.size() > 0 || changed.size() > 0) return true;
		return false;
	}
	
  public ChangedUtil(Map<K,V> local, Map<K,V> remote) {
  	Iterator remoteIterator = remote.values().iterator();
  	while (remoteIterator.hasNext()) {
  		Changed remoteObj = (Changed)remoteIterator.next();
  		Changed localObj = (Changed)local.get(remoteObj.getKey());
      if (localObj == null) {
      	added.put((K)remoteObj.getKey(), (V)remoteObj);
      } else {
      	if (!remoteObj.stillSame(localObj)) {
      		changed.put((K)remoteObj.getKey(), (V)remoteObj); 
      	}
      }
  	}
  	Iterator localIterator = local.values().iterator();
  	while (localIterator.hasNext()) {
  		Changed<K,V> localObj = (Changed<K,V>)localIterator.next();
      if (!remote.containsKey(localObj.getKey())) {
      	removed.put(localObj.getKey(), (V)localObj);
      }
  	}
  	newLocal = new HashMap<K,V>(local);
  	for (K removedKey : removed.keySet()) {
  		newLocal.remove(removedKey);
  	}
  	for (Map.Entry<K, V> changedEntry :  changed.entrySet()) {
  		newLocal.put(changedEntry.getKey(), changedEntry.getValue());
  	}
  	toDownload = new HashMap<K,V>(added);
  	toDownload.putAll(changed);
  }
}
